import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_list_widget.dart';
import 'package:gzmall_app/model/search_key.dart';

class SearchGoodsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SearchGoodsPageState();
}

class SearchGoodsPageState extends State<SearchGoodsPage> {
  double _topPadding;

  SystemUiOverlayStyle _style = SystemUiOverlayStyle.dark;
  TextEditingController _searchController;

  List<SearchKey> _searchKeys = [];

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
  }

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _getSearchKeys();
  }

  @override
  void dispose() {
    _style = SystemUiOverlayStyle.light;
    SystemChrome.setSystemUIOverlayStyle(_style);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(_style);
    init();
    return Theme(
      data: Theme.of(context).copyWith(
        canvasColor: Colors.transparent,
      ),
      child: Scaffold(
        body: Container(
          color: Colors.white,
          child: Column(children: <Widget>[
            _createSearchAppBar(),
            Expanded(
              child: ListView(
                padding:
                    const EdgeInsets.only(top: 0.0, left: 15.0, right: 15.0),
                children: <Widget>[
                  _createSearchKeysWidget("最近搜索", _searchKeys),
                ],
              ),
            ),
          ]),
        ),
      ),
    );
  }

  _createSearchAppBar() {
    return Container(
      height: 56.0 + _topPadding,
      padding: EdgeInsets.fromLTRB(10.0, _topPadding, 10.0, 0.0),
      child: Row(
        children: <Widget>[
          Expanded(
            child: GestureDetector(
              child: Container(
                height: 28.0,
                padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                margin: const EdgeInsets.only(left: 10.0, right: 10.0),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(100.0),
                    border: Border.all(color: ColorCommon.grey1)),
                child: Row(
                  children: <Widget>[
                    Padding(
                      padding: const EdgeInsets.only(right: 8.0),
                      child: Image.asset(
                        'images/search_black.png',
                        width: 16.0,
                        height: 16.0,
                      ),
                    ),
                    Expanded(
                      child: TextField(
                        controller: _searchController,
                        style: new TextStyle(color: ColorCommon.black1),
                        decoration: new InputDecoration.collapsed(
                          hintText: "搜索商品",
                          hintStyle: TextStyle(
                              fontSize: 14.0, color: ColorCommon.grey3),
                        ),
                        onSubmitted: (value) {
                          if (value != null) {
                            _addSearchKeys(value);
                          }
                        },
                      ),
                    ),
                  ],
                ),
              ),
              onTap: () {},
            ),
          ),
          GestureDetector(
            child: Text(
              "取消",
              style: TextStyle(color: ColorCommon.grey3),
            ),
            onTap: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 14.0, color: textColor),
      ),
    );
  }

  Widget _createSearchKeysWidget(String title, List<SearchKey> tags) {
    List<Widget> skuValues = [];
    if (tags != null && tags.length > 0) {
      skuValues = tags.map((item) {
        return InkWell(
          child: _getTagView(item.searchKey, ColorCommon.grey5,
              ColorCommon.grey5, ColorCommon.grey8),
          onTap: () {
            _gotoSearch(item.searchKey);
          },
          onDoubleTap: () {
            _deleteSearchKeys(item.id);
          },
        );
      }).toList();
    } else {
      skuValues.add(Align(
        child: Text("暂无搜索内容"),
        alignment: Alignment.topLeft,
      ));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          title,
          style: TextStyle(fontSize: 14.0, color: ColorCommon.grey8),
        ),
        Padding(
          padding: const EdgeInsets.only(top: 15.0, bottom: 15.0),
          child: Wrap(
            spacing: 10.0,
            runSpacing: 10.0,
            children: skuValues,
          ),
        ),
      ],
    );
  }

  _gotoSearch(String key) {
    Navigator.of(context).push(MaterialPageRoute(builder: (_) {
      return GoodsListWidget(
        searchKey: key,
      );
    }));
  }

  _getSearchKeys() {
    NetUtil.get(context, Api.userSearchKeys, (data, message) {
      if (!mounted) return;
      setState(() {
        _searchKeys = (data as List)
            ?.map((e) => e == null ? null : SearchKey.fromJson(e))
            ?.toList();
      });
    });
  }

  _addSearchKeys(String key) {
    FormData formData = new FormData.fromMap({"search_key": key});

    NetUtil.post(context, Api.userSearchKeys, (data, message) {
      ToastUtil.showMessageToast(message);

      if (!mounted) return;
      setState(() {
        _searchController.value = TextEditingValue(text: '');
        _getSearchKeys();
      });

      _gotoSearch(key);
    }, errorCallBack: (e) {
      _gotoSearch(key);
    }, params: formData, isInterceptError: false);
  }

  _deleteSearchKeys(int id) {
    NetUtil.delete(context, Api.userSearchKeys + "/" + id.toString(),
        (data, message) {
      ToastUtil.showMessageToast(message);

      if (!mounted) return;
      setState(() {
        _getSearchKeys();
      });
    });
  }
}
